package com.gutsyzhan.bilibili.aspect;

import com.gutsyzhan.bilibili.constant.AuthRoleConstant;
import com.gutsyzhan.bilibili.constant.UserMomentsConstant;
import com.gutsyzhan.bilibili.domain.UserMoments;
import com.gutsyzhan.bilibili.domain.annotation.ApiLimitedRole;
import com.gutsyzhan.bilibili.domain.auth.UserRole;
import com.gutsyzhan.bilibili.exception.ConditionException;
import com.gutsyzhan.bilibili.service.UserRoleService;
import com.gutsyzhan.bilibili.support.UserSupport;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Aspect
@Component
@Order(1)
public class DataRoleAspect {
    @Resource
    private UserSupport userSupport;

    @Resource
    private UserRoleService userRoleService;

    @Pointcut("@annotation(com.gutsyzhan.bilibili.domain.annotation.DataLimitedRole)")
    public void check(){}

    @Before("check()")
    public void doBefore(JoinPoint joinPoint){
        Long userId = userSupport.getCurrentUserId();
        List<UserRole> userRoleList = userRoleService.getUserRoleByUserId(userId);
        Set<String> userRoleCodeSet = userRoleList.stream().map(UserRole::getRoleCode).collect(Collectors.toSet());
        //获取方法传入的参数列表
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if(arg instanceof UserMoments){
                UserMoments userMoments = (UserMoments) arg;
                String type = userMoments.getType();
                if(userRoleCodeSet.contains(AuthRoleConstant.ROLE_LV0) && !UserMomentsConstant.TYPE_0.equals(type)){
                    throw new ConditionException("新手只能发布视频动态!");
                }
            }
        }
    }
}
